package com.renderbus.ep;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

import nio.NioRoot;
import nio.Service;

public class SocketThread implements Runnable {
	private Socket socket;

	public SocketThread(Socket socket) {
		this.socket = socket;
	}

	private BufferedWriter getWriter(Socket socket) throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new BufferedWriter(new OutputStreamWriter(socketOut));
	}

	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}

	public String echo(String msg) {
		return "echo:" + msg;
	}

	public void run() {
		System.out.println("-----------------Root accept command from all Client start------------------");
		try {
			System.out.println("New connection accepted "
					+ socket.getInetAddress() + ":" + socket.getPort());
			BufferedReader br = getReader(socket);
			BufferedWriter pw = getWriter(socket);
			String msg = br.readLine();
			System.out.println("Accept command is:"+msg);
//			Pipe.SinkChannel sinkChannel = NioRoot.commandNoticeNodes.sink();
//			ByteBuffer buf = ByteBuffer.allocate(512);
//			buf.clear();
//			buf.put("11111111111".getBytes());
//			buf.flip();
//			while(buf.hasRemaining()) {
//				System.out.println("233333");
//			    sinkChannel.write(buf);
//			}
			pw.write(Service.execute(msg));
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("-----------------Root accept command from all Client start end------------------");
	}
}
